package com.example.db.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * AppUtil
 */
public class AppUtil {
    private static String TAG = "appUtil";
    private static Application application;
    private volatile static List<Activity> activityList = new LinkedList<Activity>();

    public static Application getApplication() {
        if (AppUtil.application == null) {
            throw new IllegalStateException(
                    "'application' property is null,application not yet init.");
        }
        return application;
    }

    public static void setApplication(Application application) {
        if (AppUtil.application != null) {
            throw new IllegalStateException("application already holded 'application'.");
        }
        AppUtil.application = application;
    }



    public static Context getContext() {
        return application.getApplicationContext();
    }

    public static Resources getResources() {
        Context context = getContext();
        return context.getResources();
    }

    public static String getString(int resId) {
        Resources res = getResources();
        return res.getString(resId);
    }

    public static int getInteger(int resId) {
        Resources res = getResources();
        return res.getInteger(resId);
    }

    public static Drawable getColor(int resId) {
        Resources res = getResources();
        int color = res.getColor(resId);
        return new ColorDrawable(color);
    }

    public static InputStream getAssets(String resName) {
        Resources res = getResources();
        try {
            return res.getAssets().open(resName);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
            return null;
        }
    }

    //Activity加入到List中
    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public static void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    public static void finishAllActivities(Activity exceptiveActivity) {
        for (Activity activity : activityList) {
            if (activity != exceptiveActivity) {
                activity.finish();
            }
        }
    }
    //遍历每个Activity退出
    public static void exit() {
        for (Activity activity : activityList) {
            activity.finish();
        }
        System.exit(1);
    }
}
